/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * addProduct.java
 *
 * Created on Oct 31, 2011, 5:15:57 PM
 */

package giormi;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;

/**
 *
 * @author Ling
 */
public class addProduct extends javax.swing.JFrame {

    /** Creates new form addProduct */
    private F_addproduct p = new F_addproduct();
    private F_updateproduct up = new F_updateproduct();
    private MainFrame main;
    boolean update;
    private String SQLStatement;
    private Connection conn;
    private Statement stmt;
    public ResultSet rset;
    protected JTable table;
    private int idproduct;
    
    public addProduct(MainFrame mf, boolean add_update, int productid) {
        initComponents();
        this.setLocation(400, 150);
        this.setSize(350, 300);
        this.setResizable(false);
        this.setDefaultCloseOperation(javax.swing.JFrame.DO_NOTHING_ON_CLOSE);
        main = mf;
        update = add_update;
        this.idproduct = productid;

        if(update){
            up.connect();
            up.getproduct(productid);
            System.out.println("productid:"+productid);
            p_productnameField.setText(up.getP_name());
            p_packing1Field.setText(up.getpacking(1));
            p_packing2Field.setText(up.getpacking(2));
            p_packing3Combox.setSelectedItem(up.getpacking(3));
            p_barcodeField.setText(up.getP_barcode());
            p_netweightField.setText(up.getnetweight(1));
            p_netweight2Combox.setSelectedItem(up.getnetweight(2));
            p_statusCombox.setSelectedItem(up.getP_status());
        }
    }

    public void setProduct(){
        up.setP_name(p_productnameField.getText());
        up.setP_barcode(p_barcodeField.getText());
        up.setP_status((String) p_statusCombox.getSelectedItem());
        up.setP_netweight(p_netweightField.getText()+" "+(String)p_netweight2Combox.getSelectedItem());
        up.setP_packing(p_packing1Field.getText()+"x"+p_packing2Field.getText()+" "+(String)p_packing3Combox.getSelectedItem());

    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        p_netweightField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        p_packing2Field = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        p_productnameField = new javax.swing.JTextField();
        p_barcodeField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        p_packing3Combox = new javax.swing.JComboBox();
        p_saveproductButton = new javax.swing.JButton();
        p_cancelproductButton = new javax.swing.JButton();
        p_packing1Field = new javax.swing.JTextField();
        p_statusCombox = new javax.swing.JComboBox();
        p_netweight2Combox = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Manage Product");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        p_netweightField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                p_netweightFieldActionPerformed(evt);
            }
        });
        getContentPane().add(p_netweightField, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 120, 70, -1));

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("x");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 60, 50, 20));

        p_packing2Field.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                p_packing2FieldActionPerformed(evt);
            }
        });
        getContentPane().add(p_packing2Field, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 60, 30, -1));

        jLabel2.setText("Product Name");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, -1, 20));

        jLabel5.setText("Barcode");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, 70, 20));

        jLabel6.setText("Status");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, -1, 20));

        p_productnameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                p_productnameFieldActionPerformed(evt);
            }
        });
        getContentPane().add(p_productnameField, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 30, 200, -1));

        p_barcodeField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                p_barcodeFieldActionPerformed(evt);
            }
        });
        getContentPane().add(p_barcodeField, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 90, 150, -1));

        jLabel4.setText("Net Weight");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, 70, 20));

        p_packing3Combox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "g.", "kg.", "ml.", "l.", "lbs.", "oz." }));
        getContentPane().add(p_packing3Combox, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 60, 70, -1));

        p_saveproductButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/giormi/sources/Save-icon.png"))); // NOI18N
        p_saveproductButton.setText("Save");
        p_saveproductButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                p_saveproductButtonActionPerformed(evt);
            }
        });
        getContentPane().add(p_saveproductButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 190, 100, -1));

        p_cancelproductButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/giormi/sources/Button-Close-icon.png"))); // NOI18N
        p_cancelproductButton.setText("Cancel");
        p_cancelproductButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                p_cancelproductButtonActionPerformed(evt);
            }
        });
        getContentPane().add(p_cancelproductButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 220, 100, -1));

        p_packing1Field.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                p_packing1FieldActionPerformed(evt);
            }
        });
        getContentPane().add(p_packing1Field, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 60, 30, -1));

        p_statusCombox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Active", "Inactive" }));
        getContentPane().add(p_statusCombox, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 150, 150, -1));

        p_netweight2Combox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "", "g.", "kg.", "ml.", "l.", "lbs.", "oz." }));
        getContentPane().add(p_netweight2Combox, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 120, 70, -1));

        jLabel7.setText("Packing");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, 20));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void setTable(JTable table) {
        this.table = table;
    }

    public void connect(){
        try{
            DBConnection db = new DBConnection();
            conn = DBConnection.get();
            stmt = conn.createStatement();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
            JOptionPane.showMessageDialog(null,e.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
    }

    public void disconnect(){
        try {
            stmt.close();
            conn.close();
        }
        catch(Exception ex){
            System.out.println(ex.getMessage());
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
    }

    private boolean checkBarcode(String p_barcode, boolean update){

        boolean samebarcode = false;

        connect();
        try {
            if(update)
                SQLStatement = "SELECT * FROM product WHERE p_barcode = '"+p_barcode+"' "
                        + "AND idproduct!="+idproduct;
            else
                SQLStatement = "SELECT * FROM product WHERE p_barcode = '"+p_barcode+"'";
            rset = stmt.executeQuery(SQLStatement);
            if (rset.next()) {
                samebarcode = true;
                System.out.println("existing barcode " + rset.getString(p_barcode));
                return samebarcode;
            }
            rset.close();
            disconnect();
        } catch (SQLException ex) {
            Logger.getLogger(addProduct.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NullPointerException ex) {
                System.out.println("barcode null exception");
                System.out.println(ex.getMessage());
                return samebarcode;
        }
//        catch (Exception ex){
//            System.out.println("Same barcode = true");
//                warningFrame wa = new warningFrame("productexists", this);
//                wa.setVisible(true);
//                samebarcode = true;
//                return samebarcode;
//        }

        System.out.println("return same barcode " + samebarcode);
        return samebarcode;
    }

    private boolean checkNamePacking(String p_name, String p_packing, boolean update){

        boolean samenamepacking = false;

        connect();
        try {
            System.out.println(p_name+" "+p_packing);
            if (update){
                SQLStatement = "SELECT * FROM product WHERE p_name = '" + p_name
                    + "' AND p_packing = '" + p_packing + "' AND idproduct!="+idproduct;
            }
            else{
            SQLStatement = "SELECT * FROM product WHERE p_name = '" + p_name 
                    + "' AND p_packing = '" + p_packing + "'";
            }
            rset = stmt.executeQuery(SQLStatement);
            System.out.println("same packing select execute");
            if (rset.next()) {
                samenamepacking = true;
                return samenamepacking;
            }
            rset.close();
            disconnect();
            } catch (NullPointerException ex) {
                System.out.println(ex.getMessage());
                return samenamepacking;
            } catch (Exception ex){
                System.out.println("Same name packing = true");
                warningFrame wa = new warningFrame("productexists", this);
                wa.setVisible(true);
                samenamepacking = true;
                return samenamepacking;
            }
        return samenamepacking;
    }

    private boolean checkValidInputs(boolean netblank, boolean net2blank)
    {
        System.out.println("CHECKVALIDINPUTS S");
        Boolean valid = false;
        String productname, barcode_s="";
        int packing1=0, packing2=0, netweight=0;
        char[] barcode = null;

        productname = p_productnameField.getText();
        barcode_s = p_barcodeField.getText();
        warningFrame wa;

        if(barcode_s.length() != 13 || productname.length() > 200){
            wa = new warningFrame("invaliddata", this);
            wa.setVisible(true);
            return valid;
        }

        else {
            try {
                packing1 = Integer.parseInt(p_packing1Field.getText());
                System.out.println("pack1");
                packing2 = Integer.parseInt(p_packing2Field.getText());
                System.out.println("pack2");
                System.out.println("netweight:"+p_netweightField.getText()+""+netblank);
                if(!netblank){ // netweight NOT blank
                    
                    System.out.println("net S");
                    netweight = Integer.parseInt(p_netweightField.getText());
                    System.out.println("net E");
                }

                barcode = p_barcodeField.getText().toCharArray();
                for(int i=0; i<13; i++){
                    Integer.parseInt(Character.toString(barcode[i]));
                }
                System.out.println("barcode");
            }
            catch(NumberFormatException e){
                System.out.println("TESTING");
                System.out.println(e);
                wa = new warningFrame("invaliddata", this);
                wa.setVisible(true);
                valid = false;
                return valid;
            }
        }
        
        valid = true;
        
        System.out.println("CHECKVALIDINPUTS E");
        return valid;
    }
    private void p_netweightFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_p_netweightFieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_p_netweightFieldActionPerformed

    private void p_packing2FieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_p_packing2FieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_p_packing2FieldActionPerformed

    private void p_productnameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_p_productnameFieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_p_productnameFieldActionPerformed

    private void p_barcodeFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_p_barcodeFieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_p_barcodeFieldActionPerformed

    private void p_saveproductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_p_saveproductButtonActionPerformed
        // TODO add your handling code here:
        String packing;
        String p_name = p_productnameField.getText();
        warningFrame wa;
        boolean samenamepacking = false, valid=false, samebarcode=false;
        confirmFrame co;
        String ppacking = p_packing1Field.getText() +"x"+ p_packing2Field.getText() + " " +p_packing3Combox.getSelectedItem().toString();
        
        this.setEnabled(false);

        p.setP_name(p_productnameField.getText());
        p.setP_barcode(p_barcodeField.getText());
        p.setP_status((String) p_statusCombox.getSelectedItem());
        p.setP_netweight(p_netweightField.getText()+" "+(String)p_netweight2Combox.getSelectedItem());
        p.setP_packing(p_packing1Field.getText()+"x"+p_packing2Field.getText()+" "+(String)p_packing3Combox.getSelectedItem());

        if((!p_productnameField.getText().equals("")) && (!p_packing1Field.getText().equals("")) && (!p_packing2Field.getText().equals("")) && (!p_barcodeField.getText().equals("")))
        {
            samenamepacking = checkNamePacking (p_name, ppacking, update);
            samebarcode = checkBarcode (p_barcodeField.getText(), update);
            System.out.println("samenamepacking="+samenamepacking+" samebarcode="+samebarcode);
            if(samenamepacking || samebarcode){
                System.out.println("product exists");
                wa = new warningFrame("productexists", this);
                wa.setVisible(true);
            }

            else {
                boolean netblank=false, net2blank=false;
                if(p_netweightField.getText().equals("")){ // BLANK netweight
                    System.out.println("net TRUE");
                    netblank = true;
                }
                if(p_netweight2Combox.getSelectedItem().toString().equals("")){
                    net2blank=true;
                }
                    valid = checkValidInputs(netblank, net2blank);
                    if(valid){
                        if (update){
                        setProduct();
                        co = new confirmFrame(main, this, up, "product", update);
                        }
                        else
                            co = new confirmFrame(main, this, p, "product", update);
                    co.setTable(table);
                    co.setVisible(true);
                    }
            }
        }
        else {
            System.out.println("may blank");
            wa = new warningFrame("invaliddata", this);
            wa.setVisible(true);
        } 
        /*
        if (){
            warningFrame wa = new warningFrame("productexists", this);
            wa.setVisible(true);
        }
        else if (){
            warningFrame wa2 = new warningFrame("invaliddata", this);
            wa2.setVisible(true);
        }
        */
//        main.setEnabled(true);
//        this.setVisible(false);
//        this.dispose();
}//GEN-LAST:event_p_saveproductButtonActionPerformed

    private void p_cancelproductButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_p_cancelproductButtonActionPerformed
        // TODO add your handling code here:
        main.setEnabled(true);
        this.setVisible(false);
        this.dispose();
}//GEN-LAST:event_p_cancelproductButtonActionPerformed

    private void p_packing1FieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_p_packing1FieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_p_packing1FieldActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JTextField p_barcodeField;
    private javax.swing.JButton p_cancelproductButton;
    private javax.swing.JComboBox p_netweight2Combox;
    private javax.swing.JTextField p_netweightField;
    private javax.swing.JTextField p_packing1Field;
    private javax.swing.JTextField p_packing2Field;
    private javax.swing.JComboBox p_packing3Combox;
    private javax.swing.JTextField p_productnameField;
    private javax.swing.JButton p_saveproductButton;
    private javax.swing.JComboBox p_statusCombox;
    // End of variables declaration//GEN-END:variables

}
